package com.example.testdb1.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.testdb1.constant.PasswordConstant;
import com.example.testdb1.entity.Student;
import com.example.testdb1.entity.dto.PageDto;
import com.example.testdb1.entity.dto.StudentDto;
import com.example.testdb1.entity.dto.StudentLoginDto;
import com.example.testdb1.entity.vo.StudentPageVO;
import com.example.testdb1.mapper.StuMapper;
import com.example.testdb1.service.StuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class StuserviceImpl extends ServiceImpl<StuMapper, Student> implements StuService {

    @Autowired
    private StuMapper stuMapper;

    @Override
    public void add(StudentDto studentDto) {

        // if (student.getPassword() != null) {
        //     DigestUtils.md5DigestAsHex(student.getPassword().getBytes(StandardCharsets.UTF_8));
        // }else
        Student student = new Student();
        BeanUtils.copyProperties(studentDto, student);

        String password = studentDto.getPassword();
        if (password != null) {
            student.setPassword(DigestUtils.md5DigestAsHex(studentDto.getPassword().getBytes(StandardCharsets.UTF_8)));
        }else {
            student.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.PASSWORD.getBytes(StandardCharsets.UTF_8)));
        }
        stuMapper.add(student);
    }


    @Override
    public List<Student> list() {

        return stuMapper.list();
    }

    @Override
    public void delete(Long id) {
        stuMapper.delete(id);
    }

    @Override
    public void update(Student student) {
        stuMapper.update(student);
    }

    @Override
    public StudentPageVO page(PageDto pageDto) {
        //pageHelper包下的类
        // PageHelper.startPage(pageDto.getPage(), pageDto.getPageSize());
        // Page<Student> studentPage = stuMapper.page(pageDto.getStart(), pageDto.getEnd());
        //pageHelper-spring-boot-start依赖下的包
        PageHelper.startPage(pageDto.getPage(), pageDto.getPageSize());
        Page<Student> studentPage = stuMapper.page(pageDto.getStart(), pageDto.getEnd());


        return new StudentPageVO(studentPage.getPages(), studentPage.getResult());
    }

    @Override
    public Student login(StudentLoginDto studentLoginDto) {
        String password = studentLoginDto.getPassword();
        String newPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        return stuMapper.login(studentLoginDto.getSname(),newPassword);
    }


}
